import store from './store/index.js'
import config from './config.js'
import {
  getUidByToken,
  getUserInfo,
  getNextOperation,
  settingVrbt,
  service,
  getSceneVrbtInfo,
  setSceneVrbt,
  userStatus,
  operation,
  rbtManagementOperation,
  SingleAddVrbt,
  SingleAddOrbt,
  batchBind,
  getUserEnMsisdn,
  getOpenid,
  getDiamond,
  saveOpenId,
  getTimes,
  add,
  sceneStart,
  checkOperate,
  getBroadcastControlProvince,
  recommendApi
} from './service/network.js'
import { querySupportService } from './service/my/index.js'
import { clickUpload } from '@/utils/activity.js'
import { CHANNEL, SUB_CHANNEL, VERSION } from './utils/constants.js'
import { MIGU_LOCAL_KEY } from './utils/constants'
import { showModal } from './utils/toast.js'
import MD5 from 'crypto-js/md5'
const TOKEN_URL = 'https://app.pac.migu.cn/PAC/user/login'
const plugin = requirePlugin('myPlugin')
const deviceId = uni.getSystemInfoSync()?.deviceId
/**
 * 启用先设置全局id\方式\接口列表
 */
function setUnionPlugin() {
  plugin.setOptions({
    sourceId: config.MIGU_SOURCEID,
    skin: 'miguvrbt'
    // requestDomain: "https://passport.migu.cn/demoweapp"
    // requestDomain: "https://union-passport.migu-net.cn"
  })
}

// ===================================login
/**
 * 咪咕插件登录
 */
function pluginMiguLogin() {
  const str = JSON.stringify({
    sourceId: config.MIGU_SOURCEID,
    logoPath: config.PRODUCT_NAME
  })
  wx.navigateTo({
    url: 'plugin://myPlugin/migulogin?jsonStr=' + str
  })
}

function queryUidByToken(token) {
  getUidByToken(token).then(resp => {
    console.log('getUid', resp)
    if (resp.code == '000000' && resp.data) {
      const data = {
        uid: resp.data.userId,
        userInfo: resp.data,
        hasLogin: true,
        token
      }
      store.commit('login', data)
      store.dispatch('setCMCC', resp.data?.provinceCode)
      querySupportService()
      // 获取用户会员信息
      userStatus().then(data => {
        if (data.code === '000000') {
          store.dispatch('getUserStatus', data.data)
        }
      })
      // 这里判断用户是否是异网用户
      getUserInfo().then(res => {
        console.log('getUserInfo', res)
        if (res.code == '000000' && res.userInfoItem) {
          // 保存用户的非加密手机号
          data.userInfo.nickName = res.userInfoItem.nickName
          store.commit('login', data)
          try {
            uni.setStorageSync(MIGU_LOCAL_KEY, data.userInfo)
          } catch (e) {
            console.log('setStorageSync-err', e)
          }
          // store.commit("setMsisdn", res.userInfoItem.msisdn);
          store.commit('setSignature', res.userInfoItem.signature)
        }
      })
      getUserEnMsisdn().then(res => {
        console.log('getUserEnMsisdn', res)
        if (res.code == '000000') {
          store.commit('setUserEnsisdn', res.data)
        }
      })
      // 在此处查询用户是否支持彩振,只在安卓机上展示
      if (store.state.phoneType == 'android') {
        checkOperate(store.state.phoneModel).then(res => {
          console.log('checkOperate---res', res)
          if (res.code == '000000') {
            store.commit('changeIsCZ', res.data.isPopup)
          }
        })
      }
      // 查询是否存有openId,因为openid可能被绑定，这里每次都需要获取
      getOpenid().then(r => {
        if (r.openid) {
          store.commit('setOpenid', r.openid)
          saveOpenId(r.openid)
        }
      })
      getBroadcastControlProvince().then(res => {
        // 登录成功后更新一下播控权限
        if (res.code == '000000' && res.data) {
          store.commit('setBroadcastControlProvince', res.data.rightsStatus)
        }
      })
      // 获取被叫视频彩铃随机播放和单首播放模式
      console.log('获取被叫视频彩铃随机播放和单首播放模式')
      recommendApi().then(e => {
        console.log(e)
        if (e.code === '000000') {
          store.commit(
            'moduleUser/getNormalType',
            e.data['personal:passive:single:play']
          )
        }
      })
      uni.hideLoading()
    }
  })
}

function pluginGetWechatLogin(obj, callback) {
  plugin.apiMiguWechatLogin({
    sourceId: config.MIGU_SOURCEID,
    ...obj,
    // code: encodeURIComponent(res.code),
    // iv: encodeURIComponent(userResult.iv),
    // enc: encodeURIComponent(userResult.encryptedData),
    // userInfo: userInfo,
    success: result => {
      console.log('apiMiguWechatLogin', result)
      uni.hideLoading()
      uni.showToast({
        icon: 'success',
        title: '登录成功'
      })
      callback && callback()
    },
    fail: error => {
      console.log('apiMiguWechatLogin-err', error)
      uni.hideLoading()
      uni.showToast({
        title: error,
        icon: 'none'
      })
    },
    bindmsisdn: bindParam => {
      console.log('bindParam-err', bindParam)
      uni.hideLoading()
      // 需要弹出绑定框
      uni.navigateTo({
        url: `/login/pages/bindphone/index?sessionId=${bindParam.sessionId}`
      })
    }
  })
}

function pluginGetPhoneNumber(code, callback) {
  plugin.apiMsisdnLogin({
    code,
    // sourceId:"220033",
    success(miguToken) {
      console.log('code', code)
      // callback && callback(miguToken);
      // pluginApiTokenValidate(miguToken,callback);
      // queryUidByToken(miguToken)
      // 解决微信登录第一次获取token无效问题
      pluginGetToken(false)
    },
    fail(err) {
      // 失败了怎么搞呢？
      uni.hideLoading()
      uni.showModal({
        content: err,
        showCancel: false
      })
      console.error('apiMsisdnLogin-err', err)
    }
  })
}

/**
 * 插件登录成功获取token
 * @param callback  是否换取Uid,如果不换取uid则表示只刷新miguToken，则需要传入callback进行接收miguToken
 */
function pluginGetToken(needRetry, callback) {
  plugin.apiGetMiguToken({
    success(miguToken) {
      console.log('用户已登录，获取到的一级token为：', miguToken)
      if (miguToken != null) {
        // 此处返回的token有效期只有5分钟，在这里换取用户信息,无需保存token
        // callback && callback(miguToken);
        if (!callback) {
          console.log('!callback')
          queryUidByToken(miguToken)
        } else {
          console.log('callback')
          callback(miguToken)
          store.commit('login', {
            token: miguToken
          })
        }
      } else {
        // 异常分支，应该不会出现，理论上成功返回的miguToken都是有值的
        if (plugin.getMiguUserInfo() == null) {
          pluginClear()
          console.log('用户未登录，或会话已失效，需重新登录')
        } else {
          pluginClear()
          console.log('清除缓存，需重新登录')
        }
      }
    },
    fail(error) {
      uni.hideLoading()
      console.error('apiGetMiguToken', error)
      if (plugin.getMiguUserInfo() == null) {
        console.log(
          '获取一级token失败，用户未登录或会话已失效，需重新登录.',
          error
        )
        pluginClear()
      } else {
        // 如果用户已登录，但获取token失败，重试一次
        if (needRetry) {
          console.log('如果用户已登录，但获取token失败，重试一次')
          pluginGetToken(false)
          return
        }
        pluginClear()
        console.log('清除缓存，需重新登录', error)
      }
    }
  })
}

// 获取咪咕token
function getMiguToken() {
  if (!store.state.hasLogin) {
    wx.switchTab({
      url: '/pages/my/my'
    })
    toast('请先登录')
    return
  } else {
    return new Promise((resolve, reject) => {
      pluginGetToken(false, token => {
        resolve(token)
      })
    })
  }
}

/**
 * 插件清空数据
 */
function pluginClear() {
  store.dispatch('logout')
}

/**
 * 滚动到顶部
 * @param {Number} num
 */
function scrollTop(num, time) {
  uni.pageScrollTo({
    scrollTop: num || 0,
    duration: time || 0
  })
}

/**
 * 获取系统信息
 */
function getSystemInfo() {
  try {
    const sys = uni.getSystemInfoSync()
    let { platform } = sys
    if (platform == 'devtools') {
      platform = 'ios'
    }
    if (platform !== 'ios') {
      platform = 'android'
    }
    sys.platform = platform
    return sys
  } catch (e) {
    return {
      platform: 'Android_migu'
    }
  }
}

// ========================获取位置
const LOC_DATA = '30.6698676660,104.1229614820'
// getUserLoc(data => {
//   LOC_DATA = `${data.longitude}, ${data.latitude}`;
// });

/**
 * 生成请求头信息
 */

function getHttpHeader() {
  const sys = getSystemInfo()
  let { platform } = sys
  if (platform == 'devtools') {
    platform = 'ios'
  }

  if (platform !== 'ios') {
    platform = 'android'
  }
  platform = platform.substr(0, 1).toUpperCase() + platform.substr(1)
  // let msisdn = '';

  // if (store.state.userInfo && store.state.userInfo.msisdn) {
  //     msisdn = store.state.userInfo.msisdn;
  // }
  const httpHeader = {
    channel: CHANNEL,
    subchannel: SUB_CHANNEL,
    // cookie:"9499898995A1A28A639288A28A75987899938C8994A8A98B6B8D909E888198779C96858F95",
    version: VERSION, // 客户端版本号，此处传小程序版本号
    deviceId,
    // msisdn: msisdn,
    logId:
      'wxmp[' +
      (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) +
      ']', // 见logoId生成规范
    'mgm-network-operators': '02',
    'mgm-Network-standard': '03',
    'mgm-Network-type': '03',
    'location-data': LOC_DATA, // 经纬度,如果小程序获取用户位置,则使用真实位置
    ua: `${platform}_migu`, // iOS 为: Ios_migu
    IMEI: '', // 用户设备唯一识别标识15位,通过UUID产生,尽可能保证每个用户访问是固定的
    IMSI: '' // SIM卡标识.和IMEI可以保持一致
    // uid: store.state.uid
    // pacmtoken: store.state.pacmtoken,
  }
  store.state.grayTestObj.grayTest
    ? (httpHeader['Gray-test'] = '1')
    : delete httpHeader['Gray-test']
  store.state.grayTestObj.test01
    ? (httpHeader.test = '01')
    : delete httpHeader.test
  return httpHeader
}

/**
 * 显示提示
 * @param {String} content
 */
function tip(content, info) {
  if (!info) {
    info = {}
  }
  uni.showModal({
    title: info.title || '',
    content,
    showCancel: info.showCancel || false,
    cancelText: info.cancelText || '取消',
    confirmText: info.confirmText || '确定',
    success(res) {
      info.callback && info.callback(res)
    }
  })
}

/**
 * Toast提示
 * @param {String} title
 */
function toast(title, type, duration) {
  uni.showToast({
    title,
    icon: type || 'none',
    duration: duration || 2000,
    mask: true
  })
}

/**
 * 根据集团token获取用户token
 */
async function getTokenByToken() {
  const token = await getMiguToken()
  if (!token) {
    // util.toast("请先登录");
    return
  }

  const [error, res] = await uni.request({
    url: TOKEN_URL,
    header: getHttpHeader(),
    data: {
      type: '2',
      token
    }
  })
  return res.data.data
}

/**
 * 判断视频彩铃是否是高清
 */
const maplist = {
  '9:16': '013015',
  '4:03': '013029',
  '16:9': '013023',
  '1:01': '013037'
}

function isPQ(obj) {
  console.log('isPQ', obj)
  let isPQ = false
  if (obj) {
    if (obj.isHDVideo) {
      isPQ = obj.isHDVideo == 1 ? true : false
    } else {
      for (const key in maplist) {
        if (obj.aspectRatio == key) {
          if (obj.rateFormats[0].format == maplist[key]) {
            isPQ = true
          }
        }
      }
    }
  }
  return isPQ
}
/**
 * 订购视频彩铃通用方法
 * @param {*} v 视频彩铃对象
 * @param {*} page 视频彩铃来源或类型
 * @param {*} type 当视频彩铃为scene时，用于判断是否时从预览页进入
 */
async function openOrderVrbt(v, page, type) {
  console.log('openOrderVrbt---', v, page, type)
  if ((!v?.id && !v?.contentId) || !v.copyrightId) {
    toast('缺少参数id或copyrightId')
    return
  }
  if (!store.state.hasLogin) {
    uni.navigateTo({
      url: '/login/pages/login/login'
    })
    // wx.switchTab({
    // 	url: "/pages/my/my"
    // });
    // toast("请先登录");
    // 未登录跳转登录页，tabbar返回主页
    return
  }
  if (!store.state.isCMCC) {
    toast('仅支持中国移动用户')
    return
  }
  uni.showLoading({
    mask: true
  })
  // gotoSetVrbt(v, page);
  // 先判断是否是状态彩铃,下个版本增加
  if (page === 'scene') {
    // 如果是状态彩铃，需先判断用户该省份是否支持，如不支持则不需要向下执行
    // 从store取，避免重复调用接口
    const isSceneRing = store.getters['moduleUser/getSupportSceneDefault']
    checkIsSceneRing(isSceneRing, v, type)
  } else {
    checkUserSetting(v, page, type)
  }
}

function checkIsSceneRing(isSceneRing, v, type) {
  if (isSceneRing) {
    checkUserSetting(v, 'scene', type)
  } else {
    uni.hideLoading()
    tip('您所在省份暂不支持设置状态彩铃，您可在小程序中设置其他视频彩铃')
  }
}

function checkSettingType(v, page, type, gids) {
  if (page === 'scene') {
    // 设置状态彩铃
    if (type === 'preview') {
      // 区分预览里鉴权成功的返回，避免与其他冲突
      uni.$emit('scenePreview', v, type)
    } else {
      uni.$emit('sceneSet', v, type)
    }
  } else {
    // 设置普通彩铃
    settingVrbt(
      v.id || v.contentId,
      v.copyrightId,
      v.title || v.songName,
      v.resourceType
    )
      .then(res => {
        console.log('settingVrbt-success:', res, {
          page
        })
        uni.hideLoading()
        if (res.code == '000000') {
          // tip(res.info);
          // 设置成功后需要修改设置状态
          // tip("可前往【我的】-【当前在播彩铃】中查看并管理",)
          clickUpload('99')
          if (page == 'vrbt') {
            uni.$emit('setPreviewVrbtSuccess', 2)
          } else {
            uni.$emit('setVrbtSuccess', v.id || v.contentId, page, 2)
          }
          // showSetVrbtModal(2);

          // 若存在分组，则将该视频彩铃设置在分组中
          if (gids) {
            const data = {
              contentId: v.contentId || v.id,
              copyrightId: v.copyrightId,
              resourceType: v.resourceType,
              groupIds: gids
            }
            batchBind(data)
          }
        } else {
          // 1-19版本优化产品要求这样更改文案
          if (res.info.trim() == '该铃音或铃音盒已经存在（已经订购）') {
            toast('该视频已经是您的彩铃了~')
          } else if (res.info.trim() == '订购铃声已经达到最大限制') {
            tip('您的铃音数量已达上限，请删除部分铃音后再试')
          } else {
            tip(res.info)
          }
        }
      })
      .catch(err => {
        uni.hideLoading()
        console.log('settingVrbt-fail:', err)
        tip(err)
      })
  }
}
/**
 * 设置成功后的弹框提示
 * @param {Number} isScene 1为状态彩铃，2为普通彩铃
 */
// function showSetVrbtModal(isScene) {
//   tip("可以在「我的」-「在播彩铃」中查看并管理", {
//     title: "设置成功",
//     showCancel: true,
//     cancelText: "关闭",
//     confirmText: "去管理",
//     callback(res) {
//       if (res.confirm) {
//         // uni.showTabBar();
//         store.dispatch("getTabType", isScene);
//         uni.switchTab({
//           url: "/pages/my/my",
//           success() {
//             uni.$emit("gotoMyVrbt");
//           },
//         });
//       }
//     },
//   });
// }
/**
 * 设置状态彩铃
 */
function settingSceneVrbt(v, page, type) {
  // 需要先查询获取该状态彩铃的相关条件
  uni.showLoading({
    mask: true,
    title: '设置中'
  })
  if (v.situationalVrbt && v.situationalVrbt.allowEdit === '2') {
    getSceneVrbtInfo(v.id || v.contentId)
      .then(resData => {
        console.log('getSceneVrbtInfo', resData)
        if (resData.code === '000000') {
          const res = resData.data[0]
          const dataType = {
            sceneType: '1',
            sceneName: res.songName,
            ncSceneName: 1,
            startType: res.allowEdit,
            stopType: res.allowEdit,
            vrbtList: [
              {
                startMode: res.allowEdit === '2' ? '1' : '0',
                stopMode: res.allowEdit === '2' ? '1' : '0',
                contentId: res.contentId,
                copyrightId: res.copyrightId,
                resourceType: res.resourceType
              }
            ]
          }
          if (res.allowEdit === '2') {
            if (res.startWeekDay.length > 0) {
              dataType.vrbtList[0].startTime = res.startTime
              dataType.vrbtList[0].startWeekDay = res.startWeekDay
              dataType.vrbtList[0].stopTime = res.stopTime
            } else {
              dataType.vrbtList[0].startDate = res.openTime.split(' ')[0]
              dataType.vrbtList[0].startTime = res.openTime.split(' ')[1]
              dataType.vrbtList[0].stopDate = res.closeTime.split(' ')[0]
              dataType.vrbtList[0].stopTime = res.closeTime.split(' ')[1]
            }
          }
          setSceneVrbt(dataType)
            .then(res => {
              uni.hideLoading()
              console.log('setSceneVrbt', res)
              if (res.code === '000000') {
                // tip(
                //     `您已成功订购《${dataType.sceneName}》的状态彩铃`
                // );
                console.log('dadsadada=======>', {
                  type
                })
                clickUpload('98')
                if (type == 'vrbt') {
                  uni.$emit('setPreviewVrbtSuccess', 1)
                } else {
                  uni.$emit('setVrbtSuccess', v.id || v.contentId, page, 1)
                }
                // showSetVrbtModal(1);
              } else {
                tip(res.info)
              }
            })
            .catch(err => {
              uni.hideLoading()
              tip(err)
            })
        } else {
          uni.hideLoading()
          tip(res.info)
        }
      })
      .catch(err => {
        uni.hideLoading()
        tip(err)
      })
  } else {
    const nowDate = new Date().getTime()
    const data = {
      sceneName: v.songName,
      sceneType: '1',
      startType: '2',
      stopType: '2',
      ncSceneName: 1,
      vrbtList: [
        {
          copyrightId: v.copyrightId,
          startMode: '0',
          stopMode: '0',
          contentId: v.contentId || v.id,
          startTime: getTimes(nowDate)[1],
          stopTime: '',
          startDate: getTimes(nowDate)[0],
          stopDate: '',
          resourceType: v.resourceType
        }
      ]
    }
    // 今天0点时间戳
    const todayEnd = getTimes(
      nowDate - (nowDate % 86400000) - 3600000 * 8 + 86400000
    )
    if (v.endTime[0] === 0 && v.endTime[1] === 0) {
      data.vrbtList[0].stopDate = todayEnd[0]
      data.vrbtList[0].stopTime = todayEnd[1]
    } else {
      const getHour = Number(v.endTime[0] * 60 * 60) + Number(v.endTime[1] * 60)
      const getStopTime = getTimes(Number(nowDate) + getHour * 1000)
      data.vrbtList[0].stopDate = getStopTime[0]
      data.vrbtList[0].stopTime = getStopTime[1]
    }
    add(data).then(res => {
      uni.hideLoading()
      if (res.code == '000000') {
        clickUpload('98')
        uni.$emit('setVrbtSuccess', v.id || v.contentId, page, 1)
        sceneStart(res.data.sceneId)
      } else {
        tip(res.info)
      }
    })
  }
}

/**
 * 判断用户是否有设置普通彩铃的条件，有就执行设置接口，没有则跳转相关h5页面
 * @param {Object} v 视频彩铃对象数据
 * @param {String} page 视频彩铃来源，用于区分是否是状态彩铃
 */
function checkUserSetting(v, page, type) {
  getNextOperation(v.id, v.copyrightId)
    .then(res => {
      const data = {
        v,
        page,
        type,
        res
      }
      getNextCodeThen(data)
    })
    .catch(err => {
      uni.hideLoading()
      console.log('sssss', err)
    })
}

/**
 * 判断diy上传鉴权，如果有的话就进入diy设置界面，如果没有的话，就跳转相关h5页面
 */
function checkUserDiySetting(v, bool, isOvrbtSet) {
  uni.showLoading({ mask: true })
  operation(v?.activityId, isOvrbtSet)
    .then(res => {
      uni.hideLoading()
      const data = {
        v,
        res,
        operType: '21'
      }
      getNextCodeThen(data, bool)
    })
    .catch(() => {
      uni.hideLoading()
    })
}

/**
 * 管理在播彩铃及主叫鉴权
 */
function rbtManagement(v, type, operType) {
  uni.showLoading()
  rbtManagementOperation(operType)
    .then(res => {
      console.log('v,type', v, type, operType)
      uni.hideLoading()
      const data = {
        v,
        type,
        res,
        operType
      }
      getNextCodeThen(data)
    })
    .catch(() => {
      uni.hideLoading()
    })
}

/**
 * 获取到nextCode以后做的动作
 */
function getNextCodeThen(data, bool) {
  const { v, page, type, res, operType = '24' } = data
  if (res.code == '000000') {
    const { nextInfo } = res.data
    console.log('getNextCodeThen--', nextInfo)
    if (nextInfo?.bizCheckCode !== 0 && nextInfo?.bizCheckCode !== 2) {
      uni.hideLoading()
      return tip(nextInfo?.bizCodeDesc)
    }
    let nextCode = nextInfo?.nextCode
    // 彩铃包月无视频功能可能会走老流程，需判断一下弹响应弹窗
    if (nextCode == '99' && nextInfo?.proposalVrbtFunc) {
      nextCode = '2023'
    }
    // 如果nextCode为空则引导用户开通0元视频功能
    if (!nextCode) {
      nextCode = '2016'
    }
    if (bool) {
      nextCode = '2013'
    }
    console.log('nextCode', nextCode)
    const obj = {}
    // urlType 用于区分跳转的url
    if (nextCode) {
      switch (nextCode) {
        case '99': // 表示用户已具备设置彩铃条件，直接执行设置
          if (operType == '21') {
            uni.$emit('goDiyUpload', v)
            break
          }
          if (type == 'setAsideVrbtPage' || type == 'diy') {
            console.log('走设置在播彩铃接口')
            uni.hideLoading()
            // 走设置闲置在播彩铃接口
            let check = store.state.myTabCheck
            if (check == 1 || check == '') {
              if (v.status == 4 && v.copyright) {
                uni.navigateTo({
                  url: `/subDIY/pages/vrbtSetGroup/vrbtSetGroup?id=${
                    v.contentId || v.id
                  }`
                })
                return
              }
              uni.navigateTo({
                url: `/subDIY/pages/vrbtSetGroup/vrbtSetGroup?id=${
                  v.contentId || v.id
                }&isXZ=1`
              })
            }
            break
          }
          if (page != 'scene') {
            uni.hideLoading()
            uni.navigateTo({
              url: `/subDIY/pages/vrbtSetGroup/vrbtSetGroup?id=${
                v.contentId || v.id
              }&page=${page}&type=${type}`
            })
          } else {
            checkSettingType(v, page, type)
          }
          break
        case '2001': // 跳转按次两步开通页_基础会员
          obj.urlType = 2
          obj.showRbt = 8
          obj.id = v.id
          gotoSetVrbt(v, page, obj)
          break
        case '2002': // 跳转按次两步开通页_视频彩铃功能
          obj.urlType = 2
          obj.showRbt = 9
          obj.id = v.id
          gotoSetVrbt(v, page, obj)
          break
        case '2003': // 跳转包月两步开通页_基础会员"
          obj.urlType = 2
          obj.showRbt = 8
          obj.monthType = 1
          gotoSetVrbt(v, page, obj)
          break
        case '2004': // 跳转包月两步开通页_视频彩铃功能
          obj.urlType = 2
          obj.showRbt = 9
          obj.monthType = 1
          gotoSetVrbt(v, page, obj)
          break
        case '2008': // 跳转按次一步开通页_基础会员
          obj.urlType = 1
          obj.showRbt = 8
          console.log('2008', obj)
          gotoSetVrbt(v, page, obj)
          break
        case '2009': // 跳转按次一步开通页_视频彩铃功能
          obj.urlType = 1
          obj.showRbt = 9
          gotoSetVrbt(v, page, obj)
          break
        case '2011': // 跳转包月页面开通
          obj.urlType = 1
          obj.monthType = 1
          gotoSetVrbt(v, page, obj)
          break
        case '2013': // 跳转主叫开通页
          uni.$emit('openFuncPop', showType || type)
          break
        case '2016': // 0元开通包月会员
          // tip("30天免费包月功能暂未开通，敬请期待")
          uni.hideLoading()
          const showType = page == 'vrbt' || (type && type == 'vrbt')
          console.log('showType', showType, type)
          if (showType) {
            uni.$emit('showVrbtZero', type)
          } else {
            uni.$emit('showZero', type)
          }
          break
        case '2017': // 钻石会员
          uni.hideLoading()
          if (operType == '21') {
            uni.$emit('showVrbtDiamond', {
              monthType: 5,
              operType
            })
            break
          }
          if (operType == '2' || operType == '22' || operType == '30') {
            uni.$emit('showVrbtDiamon', {
              monthType: 5,
              type
            })
            break
          }
          const showType1 = page == 'vrbt' || (type && type == 'vrbt')
          if (showType1) {
            uni.$emit('showVrbtDiamond', {
              monthType: 5,
              v,
              page,
              type
            })
          } else {
            uni.$emit('showDiamond', {
              monthType: 5,
              type,
              v,
              page
            })
          }
          break
        case '2018': // 钻石会员叠加包
          uni.hideLoading()
          if (operType == '21') {
            uni.$emit('showVrbtDiamond', {
              monthType: 6,
              operType
            })
            break
          }
          if (operType == '2' || operType == '22' || operType == '30') {
            uni.$emit('showVrbtDiamon', {
              monthType: 6,
              type
            })
            break
          }
          const showType2 = page == 'vrbt' || (type && type == 'vrbt')
          if (showType2) {
            uni.$emit('showVrbtDiamond', {
              monthType: 6,
              v,
              page,
              type
            })
          } else {
            uni.$emit('showDiamond', {
              monthType: 6,
              type,
              v,
              page
            })
          }
          break
        case '2019': // 开通视频功能并设置视频彩铃 公益视频彩铃
          uni.hideLoading()
          let showType3 = page == 'vrbt' || (type && type == 'vrbt')
          if (showType3) {
            uni.$emit('showVrbtPopup', {
              b: res.data,
              v,
              page,
              type,
              code: '2019'
            })
          } else {
            uni.$emit('showVrbt', {
              b: res.data,
              v,
              page,
              type,
              code: '2019'
            })
          }
          break
        case '2022': // 只开通视频彩铃功能
          uni.hideLoading()
          if (operType == '21') {
            uni.$emit('show2022')
            break
          }
          if (operType == '2' || operType == '30') {
            uni.$emit('show20222', type)
            break
          }
          const showType4 = page == 'vrbt' || (type && type == 'vrbt')
          if (showType4) {
            uni.$emit('showVrbtPopup', {
              b: res.data,
              v,
              page,
              type,
              code: '2022'
            })
          } else {
            uni.$emit('showVrbt', {
              b: res.data,
              v,
              page,
              type,
              code: '2022'
            })
          }
          break
        case '2023': // 按次订购视频彩铃
        case '2010': // 按次订购视频彩铃
          uni.hideLoading()
          console.log(nextCode, v)
          const obj1 = {
            b: res.data,
            v,
            page,
            type,
            code: nextCode
          }
          // 前置条件为用户已开通视频彩铃功能
          console.log(nextCode, store.state.userStatus.vrbtFuncStatus)
          // proposalVrbtFunc 如果为false则表示不需要继续开功能了
          if (
            (store.state.userStatus.vrbtFuncStatus ||
              !res.data.nextInfo.proposalVrbtFunc) &&
            v?.libraryType == 3
          ) {
            uni.navigateTo({
              url: `/subDIY/pages/vrbtSetGroup/vrbtSetGroup?id=${
                v.contentId || v.id
              }&type=${type}&needPay=1`,
              success: res => {
                res.eventChannel.emit('eventPay', obj1)
              }
            })
            return
          }
          const showType6 = page == 'vrbt' || (type && type == 'vrbt')
          uni.$emit(showType6 ? 'showVrbtPopup' : 'showVrbt', obj1)
          break
        case '2030': // 数智人-延迟弹窗
        case '2025': // 权益生效中
          uni.hideLoading()
          uni.showModal({
            showCancel: false,
            content:
              res.data.nextInfo.nextDes ||
              '权益生效中，请稍后再试（30s左右）。如有疑问详询10086',
            confirmText: '我知道了'
          })
          break
        case '2027': // 数智人+视频彩铃
          getSzrPopInfo('9', '1')
          break
        case '2028': // 数智人
          getSzrPopInfo('8', '0')
          break
        case '2029': // 数智人+基础会员
          getSzrPopInfo('10', '8')
          break
        case '2038':
          if (type == 'setAsideVrbtPage' || type == 'diy') {
            console.log('走设置在播彩铃接口')
            uni.hideLoading()
            // 走设置闲置在播彩铃接口
            let check = store.state.myTabCheck
            if (check == 1 || check == '') {
              if (v.status == 4 && v.copyright) {
                uni.navigateTo({
                  url: `/subDIY/pages/vrbtSetGroup/vrbtSetGroup?id=${
                    v.contentId || v.id
                  }`
                })
                return
              }
              uni.navigateTo({
                url: `/subDIY/pages/vrbtSetGroup/vrbtSetGroup?id=${
                  v.contentId || v.id
                }&isXZ=1`
              })
            }
          } else {
            tip('异常错误码：' + nextCode + ',请联系客服人员')
          }
          break
        default:
          uni.hideLoading()
          tip('异常错误码：' + nextCode + ',请联系客服人员')
          break
      }
    }
  } else {
    uni.hideLoading()
    let message = res.info
    if (message === '电话号码参数错误，没有查询出省份信息') {
      message = '仅支持中国移动用户'
    }
    tip(message)
  }
}

// 闲置设为在播
async function setAsideOnVrbt(contentId, v, gids) {
  if (contentId) {
    try {
      uni.showLoading({
        mask: true,
        title: '设置中'
      })
      const check = store.state.myTabCheck
      if (check == 1 || check == '') {
        const res = await SingleAddVrbt(contentId)
        if (res.code == '000000') {
          uni.hideLoading()
          uni.showToast({
            icon: 'none',
            mask: true,
            title: '设置成功',
            complete: () => {
              console.log('设置视频彩铃在播成功')
              uni.$emit('setAsideOnVrbtlist')
            }
          })

          // 若存在分组，则将该视频彩铃设置在分组中
          if (gids) {
            const data = {
              contentId: v.contentId || v.id,
              copyrightId: v.copyrightId,
              resourceType: v.resourceType,
              groupIds: gids
            }
            batchBind(data)
          }
        } else {
          uni.hideLoading()
          uni.showToast({
            icon: 'none',
            title: '设置失败，请重试'
          })
        }
      } else if (check == 3) {
        const res = await SingleAddOrbt(contentId)
        if (res.code == '000000') {
          uni.hideLoading()
          uni.showToast({
            icon: 'none',
            title: '设置成功',
            complete: () => {
              console.log('设置主叫视频彩铃在播成功')
              uni.$emit('setAsideOnOvrbtlist')
            }
          })
        } else {
          uni.hideLoading()
          uni.showToast({
            icon: 'none',
            title: '设置失败，请重试'
          })
        }
      }
    } catch (error) {
      console.log('设置失败', error)
      uni.hideLoading()
      uni.showToast({
        icon: 'none',
        title: '设置失败，请重试'
      })
    }
  } else {
    uni.showToast({
      icon: 'none',
      title: '暂不支持哦！'
    })
  }
}

/**
 * @param {String} monthType
 * @param {String} showRbt
 * 2027: 数智人畅享包和视频彩铃功能开通   查询文案参数 ：showRbt=1 & monthType=9 & fromH5=1
 * 2028: 数智人畅享包开通   查询文案参数 ：showRbt=0 & monthType=8 & fromH5=1
 * 2029: 数智人畅享包和基础会员开通  查询文案参数 ：showRbt=8 & monthType=10 & fromH5=1
 */
function getSzrPopInfo(monthType, showRbt) {
  getDiamond(monthType, showRbt)
    .then(res => {
      console.log('getSzrPopInfo---', res)
      if (res.code == '000000' && res.data.pageList.length > 0) {
        const { pageList } = res.data
        const szrObj = {
          monthType,
          pageList
        }
        console.log('showSzrPop---', szrObj)
        uni.$emit('showSzrPop', szrObj)
        uni.hideLoading()
      } else {
        uni.hideLoading()
        uni.showModal({
          showCancel: false,
          confirmText: '知道了',
          content: res.info || '获取数智人权益失败，请稍后重试'
        })
      }
    })
    .catch(err => {
      console.log('getSzrPopInfo---err', err)
      uni.hideLoading()
      uni.showModal({
        showCancel: false,
        confirmText: '知道了',
        content: '获取数智人权益失败，请稍后重试'
      })
    })
}

/**
 * 重新获取token跳转至h5设置页面
 */
function gotoSetVrbt(v, page, obj) {
  pluginGetToken(false, token => {
    uni.hideLoading()
    let objStr = ''
    if (obj) {
      objStr = JSON.stringify(obj)
    }
    const url = `/pages/ordervrbt/index?id=${v?.id}&cid=${
      v?.copyrightId
    }&t=${encodeURIComponent(token)}&o=${objStr}`
    if (page === 'vrbt') {
      uni.redirectTo({
        url
      })
      return
    }
    uni.navigateTo({
      url
    })
  })
}

/**
 * @param {Object} obj pay.js中构造的对象
 */
function gotoOpenFunc(obj) {
  pluginGetToken(false, token => {
    uni.navigateTo({
      url: '/pages/ordervrbt/index',
      success: result => {
        result.eventChannel.emit('payByFun', {
          t: encodeURIComponent(token),
          o: obj
        })
      }
    })
  })
}

function clearMiguCache() {
  plugin.clearMiguCache()
}

// 计算时间差
function sjc(stopTime, startTime) {
  return new Promise(resolve => {
    const stop = stopTime.split(':')
    const start = startTime.split(':')
    let itemStopTimeAfterStartS = ''
    let itemStopTimeAfterStartH = ''
    if (Number(stop[1]) - Number(start[1]) >= 0) {
      const timeAfterStartS = Number(stop[1]) - Number(start[1])
      itemStopTimeAfterStartS =
        timeAfterStartS < 10 ? `0${timeAfterStartS}` : `${timeAfterStartS}`
      if (Number(stop[0]) - Number(start[0]) >= 0) {
        const timeAfterStartH = Number(stop[0]) - Number(start[0])
        itemStopTimeAfterStartH =
          timeAfterStartH < 10 ? `0${timeAfterStartH}` : `${timeAfterStartH}`
      } else {
        const timeAfterStartH = Number(stop[0]) + 24 - Number(start[0])
        itemStopTimeAfterStartH =
          timeAfterStartH < 10 ? `0${timeAfterStartH}` : `${timeAfterStartH}`
      }
    } else if (Number(stop[1]) - Number(start[1]) < 0) {
      if (Number(stop[0]) - Number(start[0]) >= 0) {
        const timeAfterStartS = Number(stop[1]) + 60 - Number(start[1])
        const timeAfterStartH = Number(stop[0]) - 1 - Number(start[0])
        itemStopTimeAfterStartH =
          timeAfterStartH < 10 ? `0${timeAfterStartH}` : `${timeAfterStartH}`
        itemStopTimeAfterStartS =
          timeAfterStartS < 10 ? `0${timeAfterStartS}` : `${timeAfterStartS}`
      } else {
        const timeAfterStartS = Number(stop[1]) + 60 - Number(start[1])
        const timeAfterStartH = Number(stop[0]) + 24 - 1 - Number(start[0])
        itemStopTimeAfterStartH =
          Number(timeAfterStartH) < 10
            ? `0${timeAfterStartH}`
            : `${timeAfterStartH}`
        itemStopTimeAfterStartS =
          timeAfterStartS < 10 ? `0${timeAfterStartS}` : `${timeAfterStartS}`
      }
    }
    const time = [itemStopTimeAfterStartH, itemStopTimeAfterStartS]
    resolve(time)
  })
}

function getMd5Str(text) {
  return MD5(text).toString()
}

export default {
  pluginGetWechatLogin,
  clearMiguCache,
  setUnionPlugin,
  pluginMiguLogin,
  pluginGetToken,
  scrollTop,
  getHttpHeader,
  sjc,
  tip,
  toast,
  getSystemInfo,
  openOrderVrbt,
  getMiguToken,
  pluginGetPhoneNumber,
  isPQ,
  checkUserDiySetting,
  rbtManagement,
  setAsideOnVrbt,
  checkSettingType,
  settingSceneVrbt,
  gotoSetVrbt,
  gotoOpenFunc,
  getMd5Str
}
